package com.webflux.demo.config;

import com.webflux.demo.bean.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.format.FormatterRegistry;
import org.springframework.validation.Validator;
import org.springframework.web.reactive.config.WebFluxConfigurer;

/**
 * @author H
 * @date 2023/1/15
 */
@Configuration
public class WebFluxConfig implements WebFluxConfigurer {
    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(stringUserConverter());
    }

    /**
     * 定义String -> User类型转换器
     * 如果定义为Spring Bean，Spring Boot会自动识别为类型转换器
     * @return
     */
    @Bean
    public Converter<String, User> stringUserConverter() {
        Converter<String, User> converter = new Converter<String, User>() {
            @Override
            public User convert(String src) {
                // 1-xiaoming-20-1
                String[] split = src.split("-");
                User user = new User();
                user.setId(Long.parseLong(split[0]));
                user.setUsername(split[1]);
                user.setAge(Integer.valueOf(split[2]));
                user.setGender(Integer.valueOf(split[3]));
                return user;
            }
        };
        return converter;
    }

    /**
     * 设置全局性验证器
     * @return
     */
    @Override
    public Validator getValidator() {
        return new UserValidator();
    }
}
